<template>
  <div style="display:flex;height:100vh;">
    <aside style="width:280px;padding:12px;border-right:1px solid #ddd;">
      <h3>会话</h3>
      <div>
        <button @click="createDummy">创建测试会话</button>
      </div>
      <div v-for="c in convs" :key="c.id" @click="open(c.id)" style="padding:8px;border-bottom:1px solid #eee;cursor:pointer;">
        {{ c.title || c.id }}
      </div>
    </aside>
    <div style="flex:1;display:flex;flex-direction:column;">
      <div style="flex:1;padding:12px;overflow:auto;">
        <div v-for="m in messages" :key="m.id" style="margin-bottom:8px;">
          <b>{{ m.senderId }}:</b> {{ m.content }}
        </div>
      </div>
      <div style="padding:12px;border-top:1px solid #ddd;">
        <input v-model="text" style="width:70%" @keyup.enter="send" />
        <button @click="send">发送</button>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { io } from 'socket.io-client';
import axios from 'axios';

const convs = reactive([]);
const messages = ref([]);
const text = ref('');
let socket: any = null;
let current = '';

function ensureSocket() {
  if (socket) return socket;
  const token = localStorage.getItem('token') || '';
  socket = io('http://localhost:3000', { auth: { token } });
  socket.on('connect', () => console.log('socket connected'));
  socket.on('chat:message', (m: any) => {
    if (m.conversation?.id === current) messages.value.push(m);
  });
  return socket;
}

async function loadConversations() {
  try {
    const token = localStorage.getItem('token') || '';
    const res = await axios.get('http://localhost:3000/chat/conversations', { headers: { Authorization: 'Bearer ' + token }});
    convs.splice(0, convs.length, ...res.data);
  } catch (e) {
    console.log('load convs failed', e);
  }
}

function open(cid: string) {
  current = cid;
  messages.value = [];
  ensureSocket().emit('chat:join', { conversationId: cid });
  // load recent messages (stub)
  axios.get('http://localhost:3000/chat/messages', { params: { conversationId: cid } }).then(res => {
    messages.value = res.data || [];
  }).catch(()=>{});
}

function send() {
  if (!text.value.trim() || !current) return;
  ensureSocket().emit('chat:send', { conversationId: current, content: text.value });
  text.value = '';
}

async function createDummy() {
  const id = 'conv-' + Date.now();
  convs.push({ id, title: '测试会话' });
}
loadConversations();
</script>
